<?php
/**
 * user system app
 * @author wangXi <iwisunny@gmail.com>
 * Date: 2015/12/2 22:46
 */
namespace UserSystem;

use UserSystem\Tpl\Twig;
use UserSystem\ApiMsg;

class App
{
    /**
     * 模板引擎
     * @var
     */
    protected $tpl;

    /**
     * 接口消息
     * @var
     */
    protected $msg;

    /**
     * 用户对象
     * @var
     */
    protected $account;

    public function __construct()
    {
        $this->tpl=new Twig();
        $this->msg=new ApiMsg();
    }

    public function handle($request=array()){
        //设置接受外部请求的action
        if(!isset($request['act']) || empty($request['act'])){
            $this->msg->set('info', 'bad request')->output();
        }

        $this->account=new Account();
        $action=$request['act'];

        if($action=='login'){
            //显示登录视图
            if(Input::isGet()){
                $token = $this->account->genAccessToken();
                $this->tpl->render('page', array(
                    'op_name'=>'用户登录',
                    'access_token'=>$token
                ));
            }

            //处理登录逻辑
            if(Input::isPost()){
                $this->account->setName(Input::request('username'));
                $this->account->setPassword(Input::request('password'));
                $this->account->setToken(Input::request('token'));
                $this->account->login();
            }
        }
        elseif($action=='register'){
            //显示注册视图
            if(Input::isGet()){
                $token = $this->account->genAccessToken();
                $this->tpl->render('page', array(
                    'op_name'=> '用户注册',
                    'is_reg'=>true,
                    'access_token'=>$token
                ));
            }

            //处理注册逻辑
            if(Input::isPost()){
                $this->account->setName(Input::request('username'));
                $this->account->setPassword(Input::request('password'));
                $this->account->setToken(Input::request('token'));
                $this->account->register();
            }
        }
    }


}